package com.wy2cloud.core.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * md5 加解�?
 * @author wyy
 *@version 2016-1-8
 */
public final class Md5Tools {


	/**
	 * md5 加密类型
	 * @author wyy
	 *
	 */
	public enum Md5Types{
		Byte_16,
		Byte_32;
	}
	
	/**
	 * 返回字节码数组的  Md5�?
	 * @param bytes
	 * @return
	 */
	public static String EncodeByBytes(byte[] bytes){
		String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
	}

	/***
	 * md5加密
	 * @param source
	 * @return
	 */
	public static String Encode(String source){
		return EncodeByBytes(source.getBytes());
	}
	
	/**
	 * md5加密
	 * @param source
	 * @param start
	 * @param end
	 * @return
	 */
	public static String Encode(String source,Integer start,Integer end){
		String val=Encode(source);
		Integer len=val.length();
		//System.out.println(len);
		if(start<0) start=0;
		if(end>len) end=len;
		
		return val.substring(start, end);
	}
	

	/**
	 * md5加密
	 * @param source
	 * @param md5Type
	 * @return
	 */
	public static String Encode(String source,Md5Types md5Type){
		if(md5Type== Md5Types.Byte_32){
			return Encode(source);
		}else if(md5Type== Md5Types.Byte_16){
			return Encode(source,8,24);
		}else{
			return Encode(source);
		}
	}
	

	
	public static void main(String[] args) {
	
		System.out.println(Md5Tools.Encode("aaaaaa"));
		System.out.println(Md5Tools.Encode("aaaaaa",0,32));

		System.out.println(Md5Tools.Encode("aaaaaa", Md5Types.Byte_16));

	}
}
